package com.songwo.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;

/**
 * @author zhongzheng
 * @description redis工具类
 * @date 2018/5/25 14:49
 */
@Component
public class RedisUtils {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 检查 key 是否存在
     *
     * @param key 键
     * @return
     */
    public boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 根据 key 取得 value
     *
     * @param key 键
     * @return
     */
    public Object get(String key) {
        if (this.hasKey(key)) {
            return redisTemplate.opsForValue().get(key);
        } else {
            return null;
        }
    }

    /**
     * 根据 key 保存 value
     *
     * @param key   键
     * @param value 值
     * @return
     */
    public boolean save(String key, Object value) {
        if (StringUtils.isBlank(key) || value == null) {
            return false;
        }
        redisTemplate.opsForValue().set(key, value);
        return true;
    }

    /**
     * 根据 key 删除
     *
     * @param key 键
     * @return
     */
    public boolean delete(String key) {
        if (StringUtils.isBlank(key)) {
            return false;
        }
        redisTemplate.delete(key);
        return true;
    }

    /**
     * 根据 key 删除多个
     *
     * @param keys 多个键
     * @return
     */
    public boolean delete(Collection<String> keys) {
        if (keys == null || keys.size() == 0) {
            return false;
        }
        redisTemplate.delete(keys);
        return true;
    }
}
